package com.lsq.tucao.express.utils;

import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@Component
public class SensitiveWordFilter {
	@SuppressWarnings("rawtypes")
	private Map sensitiveWordMap = null;
	public static int minMatchTYpe = 1;
	public static int maxMatchType = 2;

	public SensitiveWordFilter(){
		sensitiveWordMap = new SensitiveWordInit().initKeyWord();
	}

	public boolean isContaintSensitiveWord(String txt,int matchType){
		boolean flag = false;
		for(int i = 0 ; i < txt.length() ; i++){
			int matchFlag = this.CheckSensitiveWord(txt, i, matchType);
			if(matchFlag > 0){
				flag = true;
			}
		}
		return flag;
	}

	public Set<String> getSensitiveWord(String txt , int matchType){
		Set<String> sensitiveWordList = new HashSet<String>();
		
		for(int i = 0 ; i < txt.length() ; i++){
			int length = CheckSensitiveWord(txt, i, matchType);
			if(length > 0){
				sensitiveWordList.add(txt.substring(i, i+length));
				i = i + length - 1;
			}
		}
		
		return sensitiveWordList;
	}

	public String replaceSensitiveWord(String txt,int matchType,String replaceChar){
		String resultTxt = txt;
		Set<String> set = getSensitiveWord(txt, matchType);
		Iterator<String> iterator = set.iterator();
		String word = null;
		String replaceString = null;
		while (iterator.hasNext()) {
			word = iterator.next();
			replaceString = getReplaceChars(replaceChar, word.length());
			resultTxt = resultTxt.replaceAll(word, replaceString);
		}
		
		return resultTxt;
	}

	private String getReplaceChars(String replaceChar,int length){
		String resultReplace = replaceChar;
		for(int i = 1 ; i < length ; i++){
			resultReplace += replaceChar;
		}
		
		return resultReplace;
	}

	@SuppressWarnings({ "rawtypes"})
	public int CheckSensitiveWord(String txt,int beginIndex,int matchType){
		boolean  flag = false;
		int matchFlag = 0;
		char word = 0;
		Map nowMap = sensitiveWordMap;
		for(int i = beginIndex; i < txt.length() ; i++){
			word = txt.charAt(i);
			nowMap = (Map) nowMap.get(word);
			if(nowMap != null){
				matchFlag++;
				if("1".equals(nowMap.get("isEnd"))){
					flag = true;
					if(SensitiveWordFilter.minMatchTYpe == matchType){
						break;
					}
				}
			}
			else{
				break;
			}
		}
		if(matchFlag < 2 || !flag){
			matchFlag = 0;
		}
		return matchFlag;
	}

//	public static void main(String[] args) {
//		SensitiveWordFilter filter = new SensitiveWordFilter();
//		String string = "性爱性爱\n" +
//				"李红智\n" +
//				"梁光烈\n" +
//				"巴黎市长\n" +
//				"成人BT\n" +
//				"免注册淫色电影\n" +
//				"UltraSurf\n" +
//				"鐵血三國志\n" +
//				"性爱图库\n" +
//				"公安\n" +
//				"777黄站\n" +
//				"大龟头顶住嫂嫂的花心深处\n" +
//				"插 穴 射 喷 精液他娘的TMD";
//		Set<String> set = filter.getSensitiveWord(string, 1);
//		System.out.println("语句中包含敏感词的个数为：" + set.size() + "。包含：" + set);
//	}
}
